﻿Imports System.Text

Public Class Main

    Dim wh As WebHelper
    Dim ImgZagor, ImgTuttoZagor As Image
    Dim FileKey As Dictionary(Of Integer, String)

#Region "Contructor"
    Public Sub New()
        ' This call is required by the designer.
        InitializeComponent()
        ' Add any initialization after the InitializeComponent() call.
        wh = New WebHelper
    End Sub

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        LoadCombo()
        bFolderComics.BringToFront()
        bFolderSaveTemplate.BringToFront()
    End Sub

    Private Sub LoadCombo()
        For i As Integer = 1 To 1000
            cmbSelector.Items.Add(i.ToString.PadLeft(3, "0"))
        Next
    End Sub
#End Region

    Private Sub bLoadHtml_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bLoadHtml.Click
        Dim url As String = String.Empty
        Try
            If Not String.IsNullOrEmpty(cmbSelector.Text) Then
                url = String.Format(ConfigurationManager.AppSettings("ZagorWebSite"), Integer.Parse(cmbSelector.Text))
                wh.LoadWebPage(url)
                If wh.HtmlDoc IsNot Nothing Then
                    GetInfoFromHtml()
                End If
            End If
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "bLoad_Click")
        End Try
    End Sub

    Private Sub CleanTextControl()
        txtTitle.Text = String.Empty
        txtWriter.Text = String.Empty
        txtDesigner.Text = String.Empty
        txtPlot.Text = String.Empty
        txtYearZagor.Text = String.Empty
        txtYearTuttoZagor.Text = String.Empty
        txtCover.Text = String.Empty
    End Sub

    Private Sub GetInfoFromHtml()

        CleanTextControl()
        'GeneratedTemplate = String.Empty
        Dim imageZagorPath As String = String.Empty
        Dim imageTuttoZagorPath As String = String.Empty

        Try
            txtTitle.Text = wh.HtmlDoc.DocumentNode.SelectSingleNode(ConfigurationManager.AppSettings("FieldConstantTitle")).InnerText.Replace("&#39;", "'")
            txtWriter.Text = wh.HtmlDoc.DocumentNode.SelectSingleNode(ConfigurationManager.AppSettings("FieldConstantWriter")).InnerText.Replace("&#39;", "'")
            txtDesigner.Text = wh.HtmlDoc.DocumentNode.SelectSingleNode(ConfigurationManager.AppSettings("FieldConstantDesigner")).InnerText.Replace("&#39;", "'")
            txtPlot.Text = wh.HtmlDoc.DocumentNode.SelectSingleNode(ConfigurationManager.AppSettings("FieldConstantPlot")).InnerText.Replace("&#39;", "'")
            txtYearZagor.Text = wh.HtmlDoc.DocumentNode.SelectSingleNode(ConfigurationManager.AppSettings("FieldConstantMonthYearZagor")).InnerText.Trim.Replace("&#39;", "'")
            imageZagorPath = wh.HtmlDoc.DocumentNode.SelectSingleNode(ConfigurationManager.AppSettings("FieldConstantImageZagor")).InnerHtml.Trim
            Try
                txtYearTuttoZagor.Text = wh.HtmlDoc.DocumentNode.SelectSingleNode(ConfigurationManager.AppSettings("FieldConstantMonthYearTuttoZagor")).InnerText.Trim.Replace("&#39;", "'")
                imageTuttoZagorPath = wh.HtmlDoc.DocumentNode.SelectSingleNode(ConfigurationManager.AppSettings("FieldConstantImageTuttoZagor")).InnerHtml.Trim
            Catch ex As Exception
                txtYearTuttoZagor.Text = String.Empty
            End Try
            Try
                txtCover.Text = wh.HtmlDoc.DocumentNode.SelectSingleNode(ConfigurationManager.AppSettings("FieldConstantCoverDesigner")).InnerText.Replace("&#39;", "'")
            Catch ex As Exception
                txtCover.Text = txtDesigner.Text
            End Try
            imageZagorPath = TextBetween(imageZagorPath, "('", "'")
            ImgZagor = wh.DownloadImage(imageZagorPath)
            Try
                imageTuttoZagorPath = TextBetween(imageTuttoZagorPath, "('", "'")
                If Not String.IsNullOrEmpty(imageTuttoZagorPath) Then
                    ImgTuttoZagor = wh.DownloadImage(imageTuttoZagorPath)
                End If
            Catch ex As Exception
            End Try

            If Not String.IsNullOrEmpty(imageZagorPath) Then
                With pbZagor
                    .Image = ImgZagor
                    .SizeMode = PictureBoxSizeMode.StretchImage
                End With
            End If

            If Not String.IsNullOrEmpty(imageTuttoZagorPath) Then
                With pbTuttoZagor
                    .Image = ImgTuttoZagor
                    .SizeMode = PictureBoxSizeMode.StretchImage
                End With
            End If

        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "GetInfoFromHtml")
        Finally
            FreeMemory()
        End Try

    End Sub

    Private Sub ImagePreview(ByVal img As Image)
        Dim f As New ImagePreviewForm(img)
        f.ShowDialog()
        f = Nothing
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bTest.Click
        Dim f As New TestForm
        f.ShowDialog()
        f = Nothing
    End Sub

#Region "Drag'n Drop"
    Private Sub txtFileName_DragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles txtFileName.DragDrop
        txtFileName.Text = ""
        Dim file_names As String() = DirectCast(e.Data.GetData(DataFormats.FileDrop), String())
        For Each file_name As String In file_names
            txtFileName.Text = file_name
        Next file_name
    End Sub

    Private Sub txtFileName_DragEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles txtFileName.DragEnter
        If e.Data.GetDataPresent(DataFormats.FileDrop) Then
            e.Effect = DragDropEffects.Copy
        Else
            e.Effect = DragDropEffects.None
        End If
    End Sub

    Private Sub txtFolderExport_DragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles txtFolderExport.DragDrop
        txtFolderExport.Text = ""
        Dim file_names As String() = DirectCast(e.Data.GetData(DataFormats.FileDrop), String())
        For Each file_name As String In file_names
            txtFolderExport.Text = file_name
        Next file_name
    End Sub

    Private Sub txtFolderExport_DragEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles txtFolderExport.DragEnter
        If e.Data.GetDataPresent(DataFormats.FileDrop) Then
            e.Effect = DragDropEffects.Copy
        Else
            e.Effect = DragDropEffects.None
        End If
    End Sub

    Private Sub txtFilesFolder_DragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs)
        txtFilesFolder.Text = ""
        Dim file_names As String() = DirectCast(e.Data.GetData(DataFormats.FileDrop), String())
        For Each file_name As String In file_names
            txtFilesFolder.Text = file_name
        Next file_name
    End Sub

    Private Sub txtFilesFolder_DragEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs)
        If e.Data.GetDataPresent(DataFormats.FileDrop) Then
            e.Effect = DragDropEffects.Copy
        Else
            e.Effect = DragDropEffects.None
        End If
    End Sub
#End Region

    Private Sub bBuildTemplate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bBuildTemplate.Click
        BuildTemplate()
    End Sub

    Private Sub BuildTemplate()
        Dim Body As String = GetTemplate(Template.Body)
        Dim Params(10) As String
        Params(0) = txtTitle.Text
        Params(1) = String.Format(MyConstant.Images.WebImagePath, Integer.Parse(cmbSelector.Text).ToString.PadLeft(4, "0"))
        Params(2) = txtTitle.Text
        Params(3) = txtYearZagor.Text.Split(" ")(1)
        Params(4) = txtWriter.Text
        Params(5) = txtDesigner.Text
        Params(6) = txtCover.Text
        Params(7) = GetFileSize(txtFileName.Text)
        Params(8) = GetFileExtension(txtFileName.Text)
        Params(9) = txtPlot.Text
        Params(10) = Integer.Parse(cmbSelector.Text).ToString.PadLeft(3, "0")
        Try
            If Not String.IsNullOrEmpty(Body) Then
                Body = String.Format(Body, Params)
                If Not String.IsNullOrEmpty(Body) Then
                    TemplateSW.WriteLine(vbNewLine & Body)
                End If
            End If
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "BuildTemplate")
        End Try
    End Sub

    Private Sub pbZagor_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles pbZagor.DoubleClick, pbTuttoZagor.DoubleClick
        ImagePreview(DirectCast(sender, PictureBox).Image)
    End Sub

    Private Sub VisualizzaImmagineToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles VisualizzaImmagineToolStripMenuItem.Click
        ImagePreview(pbZagor.Image)
    End Sub

    Private Sub SalvaImmagineToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SalvaImmagineToolStripMenuItem.Click
        If sfdPicture.ShowDialog = Windows.Forms.DialogResult.OK Then
            pbZagor.Image.Save(sfdPicture.FileName)
        End If
    End Sub

    Private Sub FindFileInDictionary()
        Try
            txtFileName.Text = String.Empty
            If Not String.IsNullOrEmpty(cmbSelector.Text) Then
                If FileKey IsNot Nothing AndAlso FileKey.Count > 0 Then
                    If FileKey.ContainsKey(Integer.Parse(cmbSelector.Text)) Then
                        ' Write value of the key.
                        txtFileName.Text = FileKey.Item(Integer.Parse(cmbSelector.Text))
                    End If
                End If
            End If
        Catch ex As Exception
            txtFileName.Text = String.Empty
        End Try
    End Sub

    Private Sub cmbSelector_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbSelector.SelectedIndexChanged
        FindFileInDictionary()
    End Sub

    Private Sub txtFilesFolder_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs)
        Me.Cursor = Cursors.WaitCursor
        If Not String.IsNullOrEmpty(DirectCast(sender, TextBox).Text) Then
            FileKey = GetLocalFilesFromFolder(DirectCast(sender, TextBox).Text, "*.cbz;*.cbr")
        End If
        Me.Cursor = Cursors.Default
    End Sub

    Private Sub cmbSelector_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmbSelector.TextChanged
        FindFileInDictionary()
    End Sub

    Private Sub bExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bExit.Click
        Me.Close()
    End Sub

    Private Sub bOpenTemplate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bOpenTemplate.Click
        Try
            If Not String.IsNullOrEmpty(TemplateFile) Then
                Process.Start(TemplateFile)
            End If
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

    Private Sub bClipBoard_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bClipBoard.Click
        Try
            If Not String.IsNullOrEmpty(TemplateFile) Then
                Dim reader As New IO.StreamReader(TemplateFile)
                Dim data_object As New DataObject
                data_object.SetData(reader.ReadToEnd)
                Clipboard.Clear()
                Clipboard.SetDataObject(data_object)
            End If
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

    Private Sub bClipBoardFileName_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bClipBoardFileName.Click
        If Not String.IsNullOrEmpty(txtFileName.Text) Then
            Dim data_object As New DataObject
            data_object.SetData(txtFileName.Text)
            Clipboard.Clear()
            Clipboard.SetDataObject(data_object)
        End If
    End Sub

    Private Sub bStartTemplate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bStartTemplate.Click
        Try

            If Not String.IsNullOrEmpty(txtStart.Text) AndAlso
                Not String.IsNullOrEmpty(txtEnd.Text) AndAlso
                Not String.IsNullOrEmpty(txtFolderExport.Text) Then
                StartTemplate(txtFolderExport.Text, txtStart.Text, txtEnd.Text)
                TemplateSW.WriteLine(String.Format(GetTemplate(Template.Header), txtStart.Text, txtEnd.Text))
            Else
                MsgBox("Specificare il numero di Inizio e Fine e/o la directory di esportazione")
            End If
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

    Private Sub bEndTemplate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bEndTemplate.Click
        Try
            TemplateSW.WriteLine(vbNewLine & GetTemplate(Template.Footer))
            EndTemplate()
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

    Private Sub bFolders_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bFolderSaveTemplate.Click
        Dim fbd As New FolderBrowserDialog
        fbd.ShowNewFolderButton = True
        If fbd.ShowDialog = Windows.Forms.DialogResult.OK Then
            txtFolderExport.Text = fbd.SelectedPath
        End If
    End Sub

    Private Sub bFolderComics_Click(sender As System.Object, e As System.EventArgs) Handles bFolderComics.Click
        Dim fbd As New FolderBrowserDialog
        fbd.ShowNewFolderButton = True
        If fbd.ShowDialog = Windows.Forms.DialogResult.OK Then
            txtFilesFolder.Text = fbd.SelectedPath
        End If
    End Sub
End Class
